<?php

namespace App\Repositories;

use App\Models\ItemOrder;
use App\Models\Item;
use App\Models\ItemOrderRead;
use App\Models\Cooperation;
use App\Models\Channel;
use App\Models\ChannelOrder;
use App\Models\ChannelUser;
use InfyOm\Generator\Common\BaseRepository as iBaseRepository;
use Illuminate\Support\Facades\DB;

class ItemOrderRepository extends iBaseRepository
{
    /**
     * @var array
     */
    protected $fieldSearchable = [
        'channel_id',
        'channel_order_id',
        'house_id',
        'wechat_user_id',
        'consult_content',
        'status'
    ];

    /**
     * Configure the Model
     **/
    public function model()
    {
        return ItemOrder::class;
    }

    /**
     * 项目方用户预约列表
     */
    public function getUserOrdersForItem($itemId, $request)
    {
        $type = $request['type'] ?? 'all';
        switch ($type) {
            case 'cooperation':
                $type = 'cooperation';
                $showOrders = $this->model->select(['wechat_user_id'])
                    ->addSelect(DB::raw('MAX(id) AS id'))
                    ->addSelect(DB::raw('COUNT(id) AS num'))
                    ->where('item_id', '=', $itemId)
                    ->whereIn('channel_id', function ($query) use ($itemId) {
                        $cooperation = new Cooperation();
                        $query->select('channel_id')
                            ->from($cooperation->table)
                            ->where('item_id', $itemId)
                            ->where('status', '<>', Cooperation::STATUS_DEFAULT);
                    })
                    ->groupBy('wechat_user_id')
                    ->simplePaginate($request['limit'] ?? 20);
                break;

            case 'not_cooperation':
                $type = 'not_cooperation';
                $showOrders = $this->model->select(['wechat_user_id'])
                    ->addSelect(DB::raw('MAX(id) AS id'))
                    ->addSelect(DB::raw('COUNT(id) AS num'))
                    ->where('item_id', '=', $itemId)
                    ->whereNotIn('channel_id', function ($query) use ($itemId) {
                        $cooperation = new Cooperation();
                        $query->select('channel_id')
                            ->from($cooperation->table)
                            ->where('item_id', $itemId)
                            ->where('status', '<>', Cooperation::STATUS_DEFAULT);
                    })
                    ->groupBy('wechat_user_id')
                    ->simplePaginate($request['limit'] ?? 20);
                break;

            default:
                $type = 'all';
                $showOrders = $this->model->select(['wechat_user_id'])
                    ->addSelect(DB::raw('MAX(id) AS id'))
                    ->addSelect(DB::raw('COUNT(id) AS num'))
                    ->where('item_id', '=', $itemId)
                    ->groupBy('wechat_user_id')
                    ->simplePaginate($request['limit'] ?? 20);
                break;
        }

        $showOrders->appends(['type' => $type])->links();

        $resultOrders = $showOrders->toArray();
        $idToNum = $showOrders->pluck('num', 'id')->toArray();

        if ($resultOrders['data'])
        {
            $orders = $this->model->select(['id', 'channel_id', 'channel_order_id', 'house_id', 'wechat_user_id', 'consult_content', 'created_at'])
                ->whereIn('id', array_keys($idToNum))
                ->with('hasWechatUser')
                ->with('hasHouse')
                ->with('hasChannel')
                ->groupBy('wechat_user_id')
                ->orderBy('id', 'desc')
                ->simplePaginate($request['limit'] ?? 20);

            if ($orders)
            {
                $item = Item::find($itemId);
                $channelIds = array_unique($orders->pluck('channel_id')->toArray());
                $cooperationChannelIds = Cooperation::select(['id', 'channel_id'])
                    ->where('item_id', $itemId)
                    ->whereIn('channel_id', $channelIds)
                    ->where('status', '<>', Cooperation::STATUS_DEFAULT)
                    ->pluck('channel_id')
                    ->toArray();

                foreach ($orders as $key => $val)
                {
                    $orders[$key]['num'] = $idToNum[$val->id] ?? 0;

                    $orders[$key]['new_flag'] = ItemOrderRead::where('wechat_user_id', getLoginWxUserId())
                        ->where('item_order_id', $val->id)
                        ->first() ? 0 : 1;

                    $orders[$key]['country_num'] = 0;
                    if ($val->hasHouse)
                    {
                        $orders[$key]['country_num'] = ChannelOrder::select(['houses.country'])
                            ->join('houses', 'houses.id', '=', 'channel_orders.house_id')
                            ->where('channel_orders.wechat_user_id', $val->hasWechatUser->id)
                            ->where('houses.country', '=', $item->country ?? NULL)
                            ->count();

                        $val->hasHouse->cover = fileUrl($val->hasHouse->cover);
                        $val->hasHouse->new_flag = $orders[$key]['new_flag'];
                    }
                    $orders[$key]['house'] = $val->hasHouse;
                    unset($orders[$key]->hasHouse);

                    $orders[$key]['wechat_user'] = $val->hasWechatUser;
                    unset($orders[$key]->hasWechatUser);

                    if ($val->hasChannel)
                    {
                        $val->hasChannel->logo = fileUrl($val->hasChannel->logo);
                        $val->hasChannel->is_cooperation = in_array($val->hasChannel->id, $cooperationChannelIds) ? 1 : 0;
                    }
                    $orders[$key]['channel'] = $val->hasChannel;
                    unset($orders[$key]->hasChannel);
                }
            }

            $orders = $orders->toArray();
            $resultOrders['data'] = $orders['data'];
        }

        return $resultOrders;
    }

    /**
     * 项目方用户预约详情
     */
    public function getUserOrderForItem($id, $itemId)
    {
        $order = $this->model->select(['id', 'channel_id', 'channel_order_id', 'house_id', 'wechat_user_id', 'consult_content', 'created_at'])
            ->where('id', $id)
            ->with('hasWechatUser')
            ->with('hasChannel')
            ->first();

        if ($order)
        {
            $cooperation = Cooperation::select(['id', 'status'])
                ->where('item_id', $itemId)
                ->where('channel_id', $order->channel_id)
                ->first();

            if ( !$cooperation || $cooperation->status != Cooperation::STATUS_OPEN)
            {
                $order->hasWechatUser->phone = substr_replace($order->hasWechatUser->phone, '****', 3, 4);
            }
            $order['wechat_user'] = $order->hasWechatUser;
            unset($order->hasWechatUser);

            if ($order->hasChannel)
            {
                $order->hasChannel->logo = fileUrl($order->hasChannel->logo);
                $order->hasChannel->is_cooperation = $cooperation ? 1 : 0;
            }
            $order['channel'] = $order->hasChannel;
            unset($order->hasChannel);

            $order->user_status = ChannelUser::where('channel_id', $order->channel_id)->where('wechat_user_id', $order->wechat_user_id)->first();

            $orders = $this->model->select(['id', 'channel_id', 'channel_order_id', 'house_id', 'wechat_user_id', 'consult_content', 'created_at'])
                ->where('item_id', $itemId)
                ->where('channel_id', $order->channel_id)
                ->where('wechat_user_id', $order->wechat_user_id)
                ->with('hasHouse')
                ->orderBy('id', 'desc')
                ->simplePaginate($request['limit'] ?? 20);

            if ($orders->items())
            {
                foreach ($orders as $key => $val)
                {
                    if ($val->hasHouse)
                    {
                        $val->hasHouse->new_flag = ItemOrderRead::where('wechat_user_id', getLoginWxUserId())
                            ->where('item_order_id', $val->id)
                            ->first() ? 0 : 1;
                        $val->hasHouse->cover = fileUrl($val->hasHouse->cover);
                    }
                    $orders[$key]['house'] = $val->hasHouse;
                    unset($orders[$key]->hasHouse);
                }
            }

            $order['orders'] = $orders;
        }

        return $order;
    }

    /**
     * 添加已读记录
     */
    public function createRead($id, $itemId)
    {
        if (getLoginWxUserId())
        {
            $read = new ItemOrderRead();
            $attributes = [
                'item_id' => $itemId,
                'item_order_id' => $id,
                'wechat_user_id' => getLoginWxUserId()
            ];
            $read->firstOrCreate($attributes);
        }

        return TRUE;
    }

    /**
     * 重置未读
     */
    public function resetUnread($itemId)
    {
        if (getLoginWxUserId())
        {
            $newOrders = $this->model->select(['id'])
                ->where('item_id', $itemId)
                ->whereNotIn('id', function ($query) use ($itemId) {
                    $read = new ItemOrderRead();
                    $query->select('item_order_id')
                        ->from($read->table)
                        ->where('item_id', $itemId)
                        ->where('wechat_user_id', getLoginWxUserId())
                        ->get();
                })
                ->orderBy('id', 'asc')
                ->get();

            if ($newOrders)
            {
                foreach ($newOrders as $key => $val)
                {
                    $read = new ItemOrderRead();
                    $attributes = [
                        'item_id' => $itemId,
                        'item_order_id' => $val->id,
                        'wechat_user_id' => getLoginWxUserId()
                    ];
                    $read->firstOrCreate($attributes);
                }
            }
        }

        return TRUE;
    }

    /**
     * 渠道项目方所有用户
     */
    public function getChannelUsersForItem($itemId, $channelId, $request)
    {
        $limit = $request['limit'] ?? 10;
        $users = $this->model->select(['wechat_user_id'])
            ->addSelect(DB::raw('MAX(id) AS id'))
            ->addSelect(DB::raw('COUNT(id) AS num'))
            ->where('item_id', '=', $itemId)
            ->where('channel_id', '=', $channelId)
            ->groupBy('wechat_user_id')
            ->orderBy('id', 'desc')
            ->simplePaginate($limit);

        $usersNum = $users->pluck('num', 'wechat_user_id');
        $users = $users->toArray();

        if ($users['data'])
        {
            $orders = $this->model->select(['id', 'channel_id', 'channel_order_id', 'house_id', 'wechat_user_id', 'consult_content', 'created_at'])
                ->whereIn('id', array_column($users['data'], 'id'))
                ->with('hasWechatUser')
                ->with('hasHouse')
                ->orderBy('id', 'desc')
                ->get();

            if ($orders)
            {
                $reads = ItemOrderRead::select(['item_order_id'])
                    ->where('item_id', $itemId)
                    ->whereIn('item_order_id', $orders->pluck('id'))
                    ->where('wechat_user_id', getLoginWxUserId())
                    ->pluck('item_order_id')
                    ->toArray();

                foreach ($orders as $key => $val)
                {
                    $orders[$key]->new_flag = in_array($val->id, $reads) ? 0 : 1;
                    $orders[$key]->country_num = $usersNum[$val->hasWechatUser->id] ?? 0;

                    $orders[$key]->wechat_user = $val->hasWechatUser;
                    unset($orders[$key]->hasWechatUser);

                    $val->hasHouse->cover = fileUrl($val->hasHouse->cover);
                    $orders[$key]->house = $val->hasHouse;
                    unset($orders[$key]->hasHouse);
                }
            }
            $users['data'] = $orders->toArray();
        }

        return $users;
    }
}
